<!-- 环比 -->
<template>
    <div class="chart-container">
        <div class="table-search">
            <el-form class="form" :inline="true" style="display: flex; justify-content: space-between;">
                <div>
                    <el-form-item label="时间:">
                        <el-select
                            v-model="timeCode"
                            size="small"
                            style="width: 120px; margin-right: 6px"
                            placeholder="请选择时间"
                        >
                            <el-option
                                v-for="item in dateTypeOptions"
                                :key="item.code"
                                :label="item.name"
                                :value="item.code"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <date-pick :type="timeCode" v-model="dateTime" />
                    </el-form-item>
                </div>
                <div>
                    <el-form-item style="margin-left: 20px">
                        <el-button 
                            size="small" 
                            @click="search" 
                            type="primary"
                            icon="el-icon-search"
                        >搜索</el-button>
                    </el-form-item>
                    <el-form-item style="margin-left: 20px">
                        <el-button 
                            size="small" 
                            @click="reset"
                            icon="el-icon-refresh-left"
                            type="warning"
                        >重置</el-button>
                    </el-form-item>
                <!-- <el-form-item style="margin-left: 20px;">
                        <el-button  @click="exportDate" >导出为excel</el-button>
                    </el-form-item> -->
                </div>
            </el-form>
        </div>

        <div>
            <RlTable
                v-if="reInit"
                ref="deviceTable"
                :border="false"
                :search="false"
                :showCard="false"
                :is-pagination="false"
                :initData="false"
                :data="list"
            >
                <template #default>
                    <el-table-column prop="name" label="名称"> </el-table-column>
                    <el-table-column prop="value" :label="str1"> </el-table-column>
                    <el-table-column prop="lastValue" :label="str2"> </el-table-column>
                    <el-table-column prop="rate" label="环比（%）"> </el-table-column>
                    <el-table-column prop="diff" label="差值"> </el-table-column>
                </template>
            </RlTable>
        </div>
    </div>
</template>

<script>
    import { energyConsumptionExport } from '@/api/energyConsumptionComparing'
    import chartQoQ from '../echarts/chartQoQ.vue'
    import { findEnergySelect } from '@/api/common.js'
    import { consumptionCycle } from '@/api/contrast.js'
    import DatePick from '@/components/DatePick'
    import { transformDateCondition } from '@/utils/date'

    export default {
        name: 'MixChart',
        components: { chartQoQ, DatePick },
        props: {
            selectedNodesQOQ: {
                type: Array,
                default: () => [],
            },
            compareType: {
                type: Number,
            },
            energyType: {
                type: String,
            },
            unit: {
                type: String,
            },
        },
        data() {
            return {
                reInit: true,
                list: [],
                pre1: '当',
                pre2: '上',
                label1: '能耗（%s）',
                label2: '能耗（%s）',
                str1: '',
                str2: '',
                //unit: '',
                yAxisNameLeft: '单位（kW·h）',
                //energyType: '',
                energyTypeData: [],
                timeCode: 'day',
                dateTime: '',
                time: '',
                pickerType: 'date',
                format: 'yyyy-MM-dd',
                startTime: '',
                endTime: '',

                xData1: [],
                xData2: [],

                barData1: [],
                lineData1: [],
                barData2: [],
                lineData2: [],
                dateTypeOptions: [
                    {
                        code: 'day',
                        name: '日',
                    },
                    {
                        code: 'month',
                        name: '月',
                    },
                    // {
                    //     code: 'week',
                    //     name: '周',
                    // },
                    {
                        code: 'year',
                        name: '年',
                    },
                ],
                timeTypeArrObj: {
                    '': '',
                    day: '日',
                    week: '周',
                    month: '月',
                    year: '年',
                },
                // xData: [],
                // barData: [],
                // lineData: [],
                params: {
                    projectId: this.$store.state.projectId,
                },
                // legendData1: ['能耗'],
                legendData1: ['计量器具#1', '计量器具#2'],
                // legendData2: ['能耗费用']
            }
        },
        created() {
            // this.time = timeFormatConvert(new Date())
            // this.startTime = this.time.toString().substring(0, 10)
            // this.endTime = this.time.toString().substring(0, 10)
            const dayjs = require('dayjs')
            const currentDate = dayjs()
            const preDate = currentDate.subtract(1, 'day')
            const formattedDate = preDate.format('YYYY-MM-DD')
            this.time = formattedDate
            this.startTime = formattedDate
            this.endTime = formattedDate
            // this.unit = this.timeTypeArrObj[this.timeType]
            // this.str1 = this.pre1 + this.unit + this.label1
            // this.str2 = this.pre2 + this.unit + this.label2
            this.getEnergyTypeData()
            //this.getproductData()
        },
        computed: {},
        watch: {},
        methods: {
            checkValid() {
                if (this.selectedNodesQOQ.length === 0) {
                    this.$message.warning('请选择至少一个分项')
                    return false
                }
                if (!this.timeCode) {
                    this.$message.warning('请选择时间粒度')
                    return false
                }
                if (!this.time) {
                    this.$message.warning('请选择时间')
                    return false
                }
                // if (this.selectedNodesQOQ.length > 5) {
                //     this.$message.warning('最多只能选择5个分项')
                //     return false
                // }
                // let len = this.selectedNodesQOQ.length
                // let index = 0
                // for (index = 0; index < len; index++) {
                //     if (
                //         this.selectedNodesQOQ[index].parentId !=
                //         this.selectedNodesQOQ[(index + 1) % len].parentId
                //     ) {
                //         this.$message.warning('所选分项的父节点必须是同一个')
                //         return false
                //     }
                // }
                return true
            },
            // //改变时间
            // changeTimeType() {
            //     switch (this.timeCode) {
            //         case 'year':
            //             this.pickerType = 'year'
            //             this.format = 'yyyy'
            //             this.startTime = formatDateFun(this.time.toString().substring(0, 4))[0]
            //             this.endTime = formatDateFun(this.time.toString().substring(0, 4))[1]
            //             break
            //         case 'month':
            //             this.pickerType = 'month'
            //             this.format = 'yyyy-MM'
            //             this.startTime = formatDateFun(this.time.toString().substring(0, 7))[0]
            //             this.endTime = formatDateFun(this.time.toString().substring(0, 7))[1]
            //             break
            //         case 'week':
            //             this.pickerType = 'week'
            //             this.format = 'yyyy-WW'
            //             this.startTime = formatDateFun(this.time.toString().substring(0, 10))[0]
            //             this.endTime = formatDateFun(this.time.toString().substring(0, 10))[1]
            //             break
            //         case 'day':
            //             const dayjs = require('dayjs')
            //             const currentDate = dayjs()
            //             const preDate = currentDate.subtract(1, 'day')
            //             const formattedDate = preDate.format('YYYY-MM-DD')
            //             this.pickerType = 'date'
            //             this.format = 'yyyy-MM-dd'
            //             this.startTime = formattedDate
            //             this.endTime = formattedDate
            //             break
            //     }

            //     //this.getproductData()
            // },
            //切换颗粒度筛选数据
            changeList() {
                //this.getproductData()
                let obj = this.energyTypeData.find((item) => {
                    return item.code === this.energyType
                })
                this.yAxisNameLeft = '单位（' + obj.dictUnit + ')'
            },
            //查询能源类型
            //查询能源类型
            async getEnergyTypeData() {
                const { data: energyOptions } = await findEnergySelect(this.$store.state.projectId)
                this.energyTypeData = energyOptions
                // getfrimInformation('1').then(res => {
                //   res = res.filter(item => item.id !== 7)
                //   this.energyTypeData = res
                // })
            },
            getParams() {
                const dateResult = transformDateCondition({
                    code: this.timeCode,
                    date: this.dateTime,
                })
                this.params.startDate = dateResult.startDate
                this.params.endDate = dateResult.endDate
                this.params.subitemIds = this.selectedNodesQOQ.map((item) => item.id)
                this.params.energyTypeCode = this.energyType
                this.params.timeCode = this.timeCode
            },
            //获取产品信息
            getproductData() {
                this.reInit = false
                let timeCode = this.timeTypeArrObj[this.timeCode]
                this.str1 = this.pre1 + timeCode + this.label1
                this.str2 = this.pre2 + timeCode + this.label2
                this.str1 = this.str1.replace('%s', this.unit)
                this.str2 = this.str2.replace('%s', this.unit)
                //this.label2 = this.label2.replace('%s', this.timeTypeArrObj[this.timeType])
                this.getParams()
                consumptionCycle(this.params).then((res) => {
                    this.list = res.data
                    let that = this
                    this.$nextTick(() => {
                        this.reInit = true
                        if (this.$refs['deviceTable']) {
                            this.$refs['deviceTable'].tableData = this.list
                        }
                    })
                })
            },

            // 搜素：
            search() {
                this.loading = true
                let ret = this.checkValid()
                if (ret) {
                    this.getproductData()
                }
            },
            // 重置：
            reset() {
                //this.energyType = ''
                this.timeCode = ''
                this.time = ''
                // this.queryParams.pageSize = 10;
                this.loading = true
                //this.getproductData()
            },
            exportDate() {
                const data = {
                    compareType: this.compareType,
                    energyType: this.energyType,
                    timeCode: this.timeCode,
                    startTime: this.startTime,
                    endTime: this.endTime,
                    list: this.selectedNodesQOQ.map((item) => item.id),
                }
                energyConsumptionExport(data).then((res) => {
                    var filename = '能耗情况环比分析'
                    var result = res
                    const link = document.createElement('a')
                    let blob = new Blob([result], { type: 'application/vnd.ms-excel' })
                    link.style.display = 'none'
                    link.href = URL.createObjectURL(blob)
                    link.setAttribute('download', filename + '.xls')
                    document.body.appendChild(link)
                    link.click()
                    document.body.removeChild(link)
                })
            },
        },
    }
</script>

<style lang="scss" scoped>
    .chart-container {
        position: relative;
        width: 100%;
        height: calc((100vh - 48px) - 130px) !important;
    }
    .top {
        margin-top: 15px;
        // display: flex;
        // align-items: center;
        // .title {
        //   height: 100%;
        // }
    }
    // .form {
    //   height: 10%;
    //   width: 80%;
    //   display: flex;
    //   justify-content: space-between;
    //   align-items: center;

    //   // .title {
    //   //   height: 20%;
    //   //   width: 100%;
    //   // }

    // }

    .export {
        width: 100px;
        float: right;
        margin-top: 20px;
        margin-bottom: 20px;
    }
    .center {
        // height: 88%;
        width: 100%;
        display: flex;
        flex-direction: column;
        // justify-content: space-around;
        div {
            width: 100%;
            height: 300px;
            // overflow: hidden;
            background: #ffffff;
            box-shadow: 0px 2px 10px 0px rgba(0, 0, 0, 0.05);
            border-radius: 10px;
            padding: 10px;
            h4 {
                text-align: left;
            }
        }
    }

    .table-search ::v-deep .el-form-item {
        margin-bottom: 0!important;
        line-height: 36px !important;
        height: 36px !important;
    }
    .table-search {
        padding: 20px 15px;
    }
    ::v-deep .el-form-item__label {
        line-height: 36px !important;
        height: 36px!important;
    }
    ::v-deep .el-form-item__content {
        line-height: 36px !important;
        height: 36px !important;
    }
</style>
